package com.yonhee.datastructure.linkedList;

import java.util.Iterator;

public class DoublyLinkedListSentinel implements Iterable<Integer> {

    /**
     * 节点类
     */
    static class Node {
        Node prev;  // 上一个节点
        Node next;  // 下一个节点

        int value;

        public Node(Node prev, Node next, int value) {
            this.prev = prev;
            this.next = next;
            this.value = value;
        }
    }

    private Node head;  // 头哨兵
    private Node tail;  // 尾哨兵

    public DoublyLinkedListSentinel() {
        head = new Node(null, null, 999);
        tail = new Node(null, null, 999);
        head.next = tail;
        tail.prev = head;
    }

    public void addFirst(int val) {
        insert(0, val);
    }

    public void removeFirst() {
        remove(0);
    }

    public void addLast(int val) {
        Node last = tail.prev;
        Node cur = new Node(last, tail, val);
        last.next = cur;
        tail.prev = cur;
    }

    public void removeLast() {
        Node removed = tail.prev; // 要删除的节点
        if (removed == head) {
            throw new IllegalArgumentException("list is empty");
        }
        Node prev = removed.prev;
        prev.next = tail;
        tail.prev = prev;
    }

    public void insert(int index, int val) {
        Node prev = find(index - 1);    // 上个节点
        if (prev == null ) {
            throw illegalArgument(index);
        }
        Node next = prev.next;  // 下个节点
        Node cur = new Node(prev, next, val);
        prev.next = cur;
        next.prev = cur;
    }

    public void remove(int index) {
        Node prev = find(index - 1); // 节点前一个
        if (prev == null) {
            throw illegalArgument(index);
        }
        Node cur = prev.next; // 要删除的节点
        // 要删除的节点为尾哨兵节点
        if (cur == tail) {
            throw illegalArgument(index);
        }
        Node next =  cur.next; // 节点后一个

        prev.next = next;
        next.prev = prev;
    }

    /**
     *
     * @return
     */
    private Node find(int index) {
        int i = -1;
        for (Node cur = head; cur != tail; cur = cur.next, i++) {
            if (i == index) {
                return cur;
            }
        }
        return null;
    }

    private IllegalArgumentException illegalArgument(int index) {
        return new IllegalArgumentException(String.format("index %s 非法参数", index));
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<>() {

            private Node pointer = head.next;

            @Override
            public boolean hasNext() {
                return pointer != tail;
            }

            @Override
            public Integer next() {
                int value = pointer.value;
                pointer = pointer.next;
                return value;
            }
        };
    }
}
